import { Component, OnInit, OnDestroy } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { ComWindow } from '@shared/classes/ComWindowClass'
import { INewPageColumn } from '@shared/interfaces/common'
import { StoreNewBaseComponent } from './base/base.component'
import { StoreNewQrcodeChannelComponent } from './qrcode-channel/qrcode-channel.component'
import { StoreNewCardChannelComponent } from './card-channel/card-channel.component'
import { StoreNewEcChannelComponent } from './ec-channel/ec-channel.component'
import { StoreNewSystemComponent } from './system/system.component'
import { StoreNewSettlementComponent } from './settlement/settlement.component'
import { StoreNewUserComponent } from './user/user.component'
import { StoreNewQrcodeFuncComponent } from './qrcode-func/qrcode-func.component'
import { StoreNewCardFuncComponent } from './card-func/card-func.component'
import { StoreNewRiskControlComponent } from './risk-control/risk-control.component'
import { StoreDataService } from '../store-data.service'
import { StoreService } from '../store.service'
import { PageService } from '@shared/services/page.service'
import { encryptPassword } from 'app/utils/helpers'
import { User } from '@shared/interfaces/user'
import { I18NService } from '@core'
import { IMCC } from '@shared/components/mcc-select/mcc-select.interface'
import { EPaymentBrand } from '@shared/enums'
import { SettleTime, ESettleTime } from '@shared/interfaces/store'

@Component({
  selector: 'app-store-new',
  templateUrl: './new.component.html',
})
export class StoreNewComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private msgSrv: NzMessageService,
    private storeStoreService: StoreDataService,
    private storeService: StoreService,
    private pageService: PageService,
    private i18n: I18NService,
  ) {}

  ngOnInit() {
    this.initColumns()
  }

  ngOnDestroy() {
    this.storeStoreService.reset()
  }

  initColumns(): void {
    this.pages = [
      {
        component: new ComWindow(StoreNewSystemComponent, { title: 'GENERAL.INFO.OTHER.SYSTEM_INFO' }),
      },
      {
        component: new ComWindow(StoreNewBaseComponent, { title: 'GENERAL.INFO.OTHER.BASIC_CONFIG' }),
      },
      {
        component: new ComWindow(StoreNewQrcodeChannelComponent, { title: 'BIZ.ACQUIRER.OTHER.QR_CHANNELS' }),
      },
      {
        component: new ComWindow(StoreNewCardChannelComponent, { title: 'BIZ.ACQUIRER.OTHER.CARD_CHANNELS' }),
      },
      {
        component: new ComWindow(StoreNewEcChannelComponent, { title: 'BIZ.ACQUIRER.OTHER.EC_CHANNELS' }),
      },
      {
        component: new ComWindow(StoreNewSettlementComponent, { title: 'GENERAL.INFO.OTHER.SETTLEMENT' }),
      },
      // {
      //   component: new ComWindow(StoreNewQrcodeFuncComponent, { title: 'GENERAL.INFO.OTHER.QR_FEATURES' }),
      // },
      // {
      //   component: new ComWindow(StoreNewCardFuncComponent, { title: '刷卡交易类型功能配置' }),
      // },
      {
        component: new ComWindow(StoreNewRiskControlComponent, { title: 'GENERAL.INFO.OTHER.RISK_CONTROL' }),
      },
      {
        component: new ComWindow(StoreNewUserComponent, { title: 'GENERAL.INFO.OTHER.USERS' }),
      },
    ]
  }

  submit(): void {
    const newStore = this.storeStoreService.value
    const replaceMcc = newStore.store.common.mcc as IMCC
    newStore.store.common.mcc = replaceMcc.mccCode
    if (newStore.cardChannels.length > 0) {
      newStore.cardChannels.forEach(channel => {
        const mcc = channel.mcc as IMCC
        channel.mcc = mcc.mccCode
      })
    }
    if (newStore.qrChannels.length > 0) {
      newStore.qrChannels.forEach(channel => {
        if (channel.chanCode === EPaymentBrand.TrueMoney) {
          if (!channel.chanMerParams.payNearby) {
            delete channel.chanMerParams.shopID
          }
        }
        if (channel.chanCode !== EPaymentBrand.TrueMoney) {
          const mcc = channel.mcc as IMCC
          channel.mcc = mcc.mccCode
        }
      })
    }
    // 转换结算时间字段类型
    if (newStore.store.common.settlement.settleTime) {
      const settleTime = newStore.store.common.settlement.settleTime as ESettleTime
      const time = settleTime.substring(3, 5) + ':00'
      const newSettleTime = new SettleTime(time, time)
      if (settleTime === ESettleTime.GMT01 || settleTime === ESettleTime.GMT02) {
        newSettleTime.tradeDayFrom = 'T'
        newSettleTime.tradeDayTo = 'T+1'
      }
      newStore.store.common.settlement.settleTime = newSettleTime
    }

    delete newStore.selectedPostRiskScheme
    // encrypt user password
    // 修改密码时修改了源数据，解决方法发送请求时进行深拷贝(原deepcopy使用场景太局限了)
    try {
      const sendData = JSON.parse(JSON.stringify(newStore))
      sendData.users.forEach((user: User) => {
        user.password = encryptPassword(user.password)
      })
      this.storeService.create(sendData).subscribe(merchant => {
        /** 成功后不需要路由守卫 */
        this.pageService.triggerGuardAlive(false)
        this.router.navigate(['../'], { relativeTo: this.route })
      })
    } catch (error) {
      this.msgSrv.success(this.trans('GENERAL.NOTIFICATION.CREATE_FAIL'))
    }
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
